package com.rc.saas.tenant.controller.tenant;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.component.UidGenerator;
import com.rc.saas.tenant.common.utils.MD5Utils;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.tenant.*;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.search.tenant.TenantUserSearch;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.sms.TenantSmsRecordService;
import com.rc.saas.tenant.service.sms.TenantSmsService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantUserService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.tenant.TenantUserVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author wangzhengwei
 * @create 2021/7/27
 */
@Controller
@RequestMapping("/tenant/user")
public class TenantUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String prefix = "/templates/tenant/user";

    @Autowired
    private UploadComponent uploadComponent;

    @Autowired
    private TenantUserService tenantUserService;

    @Autowired
    private TenantRoleService tenantRoleService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private TenantSmsRecordService tenantSmsRecordService;

    @Autowired
    private TenantSmsService tenantSmsService;

    @Autowired
    private UidGenerator uidGenerator;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, BaseSearch baseSearch) {
        TenantRoleExample tenantRoleExample = new TenantRoleExample();
        tenantRoleExample.createCriteria().andTenantCodeEqualTo(baseSearch.getTenantCode());
        List<TenantRole> tenantRoleList = tenantRoleService.selectByExample(tenantRoleExample);
        TenantUser user = ShiroUtils.getSessionUser();
        model.addAttribute("tenantRoleList", tenantRoleList);
        model.addAttribute("userType", user.getUserType());
        return prefix + "/user";
    }

    @ResponseBody
    @RequestMapping(value = "/listPageTenantUser", method = RequestMethod.GET)
    public WebPageInfo listPageTenantUser(TenantUserSearch tenantUserSearch) {
        PageInfo<TenantUserVo> page = tenantUserService.listPageTenantUser(tenantUserSearch);
        WebPageInfo webPageInfo = new WebPageInfo(page.getList(), Long.valueOf(page.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出平台用户列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(TenantUserSearch tenantUserSearch, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(tenantUserSearch);
            PageInfo<TenantUserVo> page = tenantUserService.listPageTenantUser(tenantUserSearch);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("平台用户列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TenantUserVo.class).sheet("平台用户列表").doWrite(page.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出平台用户列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    @RequestMapping("/info")
    public String info(Model model) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        TenantRole role = tenantRoleService.selectByPrimaryKey(tenantUser.getTenantRoleId());
        tenantUser = tenantUserService.selectByPrimaryKey(tenantUser.getTenantUserId());
        TenantRoleExample tenantRoleExample = new TenantRoleExample();
        tenantRoleExample.createCriteria().andTenantCodeEqualTo(tenantUser.getTenantCode());
        List<TenantRole> tenantRoleList = tenantRoleService.selectByExample(tenantRoleExample);
        model.addAttribute("tenantRoleList", tenantRoleList);

        if ("3".equals(role.getRoleType())) {
            //查询企业会员
            EnterpriseMember enterpriseMember = enterpriseMemberService.selectByPrimaryKey(tenantUser.getEnterpriseId());
            tenantUser.setRealName(enterpriseMember.getContactName());
        }
        model.addAttribute("tenantUser", tenantUser);
        model.addAttribute("role", role);
        return prefix + "/userInfo";
    }


    /**
     * 新增
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/addTenantUser", method = RequestMethod.GET)
    public String addTenantUser(Model model, BaseSearch baseSearch) {
        TenantRoleExample example = new TenantRoleExample();
        example.createCriteria().andRoleTypeEqualTo("1");
        example.setOrderByClause("sort");
        List<TenantRole> roles = tenantRoleService.selectByExample(example);

        model.addAttribute("roles", roles);
        return prefix + "/addTenantUser";
    }

    @RequestMapping(value = "/editTenantUser/{TenantUserId}", method = RequestMethod.GET)
    public String editTenantRole(@PathVariable("TenantUserId") Long TenantUserId, Model model) {
        TenantUser tenantUser = tenantUserService.selectByPrimaryKey(TenantUserId);

        TenantRoleExample tenantRoleExample = new TenantRoleExample();
        tenantRoleExample.createCriteria().andRoleTypeEqualTo("1");
        tenantRoleExample.setOrderByClause("sort");
        List<TenantRole> roles = tenantRoleService.selectByExample(tenantRoleExample);
        model.addAttribute("tenantUser", tenantUser);
        model.addAttribute("roles", roles);
        return prefix + "/editUser";
    }

    /**
     * 保存
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public TResponse save(TenantUser tenantUser, @RequestParam(value = "file", required = false) MultipartFile file) {
        String password = tenantUser.getPassword();

        if (file != null && file.getSize() != 0 && file.getContentType().contains("image")) {
            String imgUrl = uploadComponent.uploadFile(tenantUser.getTenantCode(), file);
            tenantUser.setHeadImg(imgUrl);
        }

        if (password != null) {
            tenantUser.setPassword(null);

            if (tenantUser.getTenantUserId() != null) {
                String oldPwd = tenantUserService.selectByPrimaryKey(tenantUser.getTenantUserId()).getPassword();

                String newPwd = MD5Utils.encrypt(tenantUser.getLoginName(), password);
                if (oldPwd != null && !oldPwd.equals(password)) {
                    tenantUser.setPassword(newPwd);
                }
            } else {
                tenantUser.setPassword(MD5Utils.encrypt(tenantUser.getLoginName(), password));
            }
        }
        if (tenantUser.getTenantUserId() != null) {
            try {
                tenantUserService.updateByPrimaryKeySelective(tenantUser);
            } catch (Exception e) {
                logger.error("运营商更新失败", e);
                return TResponse.FAIL("运营商账号更新失败");
            }
        } else {
            try {
                TenantUserExample tenantUserExample = new TenantUserExample();
                tenantUserExample.createCriteria().andMobileEqualTo(tenantUser.getMobile());
                long mobileCount = tenantUserService.countByExample(tenantUserExample);
                if (mobileCount > 0) {
                    return TResponse.FAIL("该手机号码已被使用");
                }
                TenantUserExample tenantUserExample2 = new TenantUserExample();
                tenantUserExample2.createCriteria().andLoginNameEqualTo(tenantUser.getLoginName());
                long loginNameCount = tenantUserService.countByExample(tenantUserExample2);
                if (loginNameCount > 0) {
                    return TResponse.FAIL("该登录名已被使用");
                }
                tenantUser.setUserType("3");//运营商新增的用户
                tenantUserService.insertSelective(tenantUser);
            } catch (Exception e) {
                logger.error("运营商账号创建失败", e);
                return TResponse.FAIL("运营商账号创建失败");
            }

        }
        return TResponse.SUCCESS();
    }

    /**
     * 重置密码
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
    @ResponseBody
    public TResponse resetPwd(HttpServletRequest request, Long id, String newPassword) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (user.getTenantUserId().toString().equals(id)) {
            return TResponse.FAIL("不能重置自己密码");
        }


        TenantUser findUser = tenantUserService.selectByPrimaryKey(id);
        Tenant tenant = tenantService.selectByTenantCode(findUser.getTenantCode());
        //登录名称统一为小写
        findUser.setLoginName(StringUtils.lowerCase(findUser.getLoginName()));

//        if (StringUtils.isBlank(findUser.getMobile()) || !findUser.getMobile().matches(HttpConstant.MOBILE_REGEX)) {
//            return TResponse.FAIL("手机号格式不正确");
//        }

        try {
            //六位随机数
            //int randMun = (int) ((Math.random() * 9 + 1) * 100000);
            //String password = String.valueOf(randMun);


            //加密密码
            TenantUser newUser = new TenantUser();
            newUser.setTenantUserId(findUser.getTenantUserId());
            newUser.setPassword(MD5Utils.encrypt(findUser.getLoginName(), newPassword));
            tenantUserService.updateByPrimaryKeySelective(newUser);

            /*//发送手机号码
            SendSmsResponse sendResult = AliyunSmsUtil.sendSms("13242452314", password, AliyunSmsTemplateEnum.RESET_PWD, new JSONObject());
            if (sendResult == null) {
                logger.error("短信系统异常");
                return TResponse.FAIL("短信系统异常");
            }
            if ("OK".equals(sendResult.getCode())){
                //短信发送记录
                TenantSmsRecord tenantSmsRecord = new TenantSmsRecord();
                tenantSmsRecord.setTenantCode(user.getTenantCode());
                tenantSmsRecord.setMobile(findUser.getMobile());
                tenantSmsRecord.setRecordType("0");
                tenantSmsRecord.setContent("tenantUser,resetPwd:重置密码");
                tenantSmsRecordService.insertSelective(tenantSmsRecord);

                //短信发送数量
                TenantSms tenantSms = tenantSmsService.selectByPrimaryKey(user.getTenantCode());
                if (tenantSms != null){
                    Long usedAmout = tenantSms.getUsedAmout().longValue() + 1;
                    Long amout = tenantSms.getAmount().longValue() - 1;
                    tenantSms.setUsedAmout(usedAmout);
                    tenantSms.setAmount(amout);
                    tenantSmsService.updateByPrimaryKeySelective(tenantSms);
                }else {
                    tenantSms.setTenantCode(user.getTenantCode());
                    tenantSms.setAmount(Long.valueOf(1));
                    tenantSms.setUsedAmout(Long.valueOf(-1));
                }
            }*/

        } catch (Exception e) {
            return TResponse.FAIL("操作失败");
        }

        return TResponse.SUCCESS();
    }

    /**
     * 删除
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.POST)
    @ResponseBody
    public TResponse remove(HttpServletRequest request, Long id) {

        TenantUser user = ShiroUtils.getSessionUser();
        if (user.getTenantUserId().equals(id)) {
            return TResponse.FAIL("不能删除自己的账户");
        }
        TenantUser tenantUser = tenantUserService.selectByPrimaryKey(id);
        if (!user.getTenantCode().equals(tenantUser.getTenantCode())) {
            return TResponse.FAIL("删除失败。所要删除的账号属于其他运营商，无权删除");
        }
        try {
            tenantUserService.deleteByPrimaryKey(id);
        } catch (Exception e) {
            return TResponse.FAIL("删除失败");
        }

        return TResponse.SUCCESS();
    }

    /**
     * 更改用户状态
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateUserStatus", method = RequestMethod.POST)
    public TResponse updateUserStatus(Long id, String status) {
        TenantUser tenantUser = tenantUserService.selectByPrimaryKey(id);
        tenantUser.setStatus(status);
        tenantUser.setLastUpdatedTime(new Date());
        tenantUserService.updateByPrimaryKey(tenantUser);
        return TResponse.SUCCESS();
    }
}
